package com.gcloud.controller.network.handler.api.network.standard;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcloud.controller.ResourceIsolationCheck;
import com.gcloud.controller.enums.ResourceIsolationCheckType;
import com.gcloud.controller.network.service.IVpcService;
import com.gcloud.controller.utils.ApiUtil;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.core.handle.ApiHandler;
import com.gcloud.core.handle.MessageHandler;
import com.gcloud.core.util.BeanUtil;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.ApiVersion;
import com.gcloud.header.Module;
import com.gcloud.header.SubModule;
import com.gcloud.header.network.model.VpcsItemType;
import com.gcloud.header.network.model.standard.StandardVpcType;
import com.gcloud.header.network.msg.api.DescribeVpcsMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeVpcsMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeVpcsReplyMsg;

@ApiHandler(module=Module.ECS,subModule=SubModule.VPC,action="DescribeVpcs", versions = {ApiVersion.Standard})
@ResourceIsolationCheck(resourceIsolationCheckType = ResourceIsolationCheckType.ROUTER, resourceIdField = "vpcIds")
public class StandardApiDescribeVpcsHanlder extends MessageHandler<StandardApiDescribeVpcsMsg, StandardApiDescribeVpcsReplyMsg>{

	@Autowired
	IVpcService service;
	
	@Override
	public StandardApiDescribeVpcsReplyMsg handle(StandardApiDescribeVpcsMsg msg) throws GCloudException {
		PageResult<VpcsItemType> response = service.describeVpcs(toParams(msg));
		PageResult<StandardVpcType> stdResponse = ApiUtil.toPage(response, toStandardReply(response.getList()));
		
		StandardApiDescribeVpcsReplyMsg reply = new StandardApiDescribeVpcsReplyMsg();
        reply.init(stdResponse);
		return reply;
	}
	
	public DescribeVpcsMsg toParams(StandardApiDescribeVpcsMsg msg) {
		DescribeVpcsMsg params = BeanUtil.copyProperties(msg, DescribeVpcsMsg.class);
		return params;
	}
	
	public List<StandardVpcType> toStandardReply(List<VpcsItemType> list) {
		if(null == list) {
			return null;
		}
		
		List<StandardVpcType> stdList = new ArrayList<>();
		
		for (VpcsItemType item : list) {
			StandardVpcType tmp = BeanUtil.copyProperties(item, StandardVpcType.class);
			stdList.add(tmp);
		}
		return stdList;
	}

}
